#!/bin/bash

# Linux权限维持一键化测试 - 全套测试运行脚本
# 版本: v1.0
# 作者: HackerPermKeeper T00ls Team
# 日期: 2023-12-01

set -e  # 遇到错误立即退出

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# 全局变量
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LOG_DIR="${SCRIPT_DIR}/../logs"
REPORT_DIR="${SCRIPT_DIR}/../reports"
BACKUP_DIR="${SCRIPT_DIR}/../backup"
TEST_SESSION_ID="$(date +%Y%m%d_%H%M%S)"

# 创建必要目录
mkdir -p "$LOG_DIR" "$REPORT_DIR" "$BACKUP_DIR"

# 日志函数
log() {
    local level=$1
    shift
    local message="$*"
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    
    case $level in
        "INFO")
            echo -e "${GREEN}[INFO]${NC} ${timestamp} - $message" | tee -a "$LOG_DIR/run_all_tests_${TEST_SESSION_ID}.log"
            ;;
        "WARN")
            echo -e "${YELLOW}[WARN]${NC} ${timestamp} - $message" | tee -a "$LOG_DIR/run_all_tests_${TEST_SESSION_ID}.log"
            ;;
        "ERROR")
            echo -e "${RED}[ERROR]${NC} ${timestamp} - $message" | tee -a "$LOG_DIR/run_all_tests_${TEST_SESSION_ID}.log"
            ;;
        "DEBUG")
            if [[ "${DEBUG:-0}" == "1" ]]; then
                echo -e "${BLUE}[DEBUG]${NC} ${timestamp} - $message" | tee -a "$LOG_DIR/run_all_tests_${TEST_SESSION_ID}.log"
            fi
            ;;
        *)
            echo -e "${CYAN}[LOG]${NC} ${timestamp} - $message" | tee -a "$LOG_DIR/run_all_tests_${TEST_SESSION_ID}.log"
            ;;
    esac
}

# 显示横幅
show_banner() {
    echo -e "${PURPLE}"
    cat << 'EOF'
╔══════════════════════════════════════════════════════════════╗
║                Linux权限维持一键化测试套件                    ║
║                HackerPermKeeper T00ls v7.0                  ║
║                                                              ║
║  功能: 全面测试Linux权限维持一键化部署功能                    ║
║  包含: 功能测试 + 隐蔽性测试 + 清理验证                      ║
╚══════════════════════════════════════════════════════════════╝
EOF
    echo -e "${NC}"
}

# 检查系统要求
check_requirements() {
    log "INFO" "检查系统要求..."
    
    # 检查root权限
    if [[ $EUID -ne 0 ]]; then
        log "ERROR" "此脚本需要root权限运行"
        echo -e "${RED}请使用 sudo 运行此脚本${NC}"
        exit 1
    fi
    
    # 检查Python版本
    if ! command -v python3 &> /dev/null; then
        log "ERROR" "Python3 未安装"
        exit 1
    fi
    
    local python_version=$(python3 -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')")
    log "INFO" "Python版本: $python_version"
    
    # 检查必需工具
    local required_tools=("systemctl" "crontab" "ssh-keygen" "ps" "netstat")
    for tool in "${required_tools[@]}"; do
        if ! command -v "$tool" &> /dev/null; then
            log "WARN" "工具 $tool 未找到，某些测试可能失败"
        else
            log "DEBUG" "工具 $tool 已安装"
        fi
    done
    
    # 检查测试脚本
    local test_scripts=("linux_persistence_tester.py" "persistence_stealth_checker.py" "persistence_cleanup_verifier.py")
    for script in "${test_scripts[@]}"; do
        if [[ ! -f "$SCRIPT_DIR/$script" ]]; then
            log "ERROR" "测试脚本 $script 未找到"
            exit 1
        fi
    done
    
    log "INFO" "系统要求检查完成"
}

# 备份系统状态
backup_system_state() {
    log "INFO" "备份系统状态..."
    
    local backup_session_dir="$BACKUP_DIR/backup_${TEST_SESSION_ID}"
    mkdir -p "$backup_session_dir"
    
    # 备份SSH配置
    if [[ -f ~/.ssh/authorized_keys ]]; then
        cp ~/.ssh/authorized_keys "$backup_session_dir/authorized_keys.bak" 2>/dev/null || true
    fi
    
    # 备份crontab
    crontab -l > "$backup_session_dir/crontab.bak" 2>/dev/null || echo "# No crontab" > "$backup_session_dir/crontab.bak"
    
    # 备份systemd服务列表
    systemctl list-unit-files --type=service > "$backup_session_dir/systemd_services.bak"
    
    # 备份profile.d目录
    if [[ -d /etc/profile.d ]]; then
        ls -la /etc/profile.d/ > "$backup_session_dir/profile_d.bak"
    fi
    
    # 备份bashrc
    if [[ -f ~/.bashrc ]]; then
        cp ~/.bashrc "$backup_session_dir/bashrc.bak"
    fi
    
    log "INFO" "系统状态备份完成: $backup_session_dir"
}

# 运行功能测试
run_functionality_tests() {
    log "INFO" "开始运行功能测试..."
    
    local test_output_dir="$REPORT_DIR/functionality_${TEST_SESSION_ID}"
    mkdir -p "$test_output_dir"
    
    echo -e "${BLUE}正在运行Linux权限维持功能测试...${NC}"
    
    if python3 "$SCRIPT_DIR/linux_persistence_tester.py" --output "$test_output_dir" 2>&1 | tee "$LOG_DIR/functionality_test_${TEST_SESSION_ID}.log"; then
        log "INFO" "功能测试完成"
        return 0
    else
        log "ERROR" "功能测试失败"
        return 1
    fi
}

# 运行隐蔽性测试
run_stealth_tests() {
    log "INFO" "开始运行隐蔽性测试..."
    
    local test_output_dir="$REPORT_DIR/stealth_${TEST_SESSION_ID}"
    mkdir -p "$test_output_dir"
    
    echo -e "${BLUE}正在运行权限维持隐蔽性测试...${NC}"
    
    if python3 "$SCRIPT_DIR/persistence_stealth_checker.py" --output "$test_output_dir" 2>&1 | tee "$LOG_DIR/stealth_test_${TEST_SESSION_ID}.log"; then
        log "INFO" "隐蔽性测试完成"
        return 0
    else
        log "ERROR" "隐蔽性测试失败"
        return 1
    fi
}

# 运行清理验证测试
run_cleanup_tests() {
    log "INFO" "开始运行清理验证测试..."
    
    local test_output_dir="$REPORT_DIR/cleanup_${TEST_SESSION_ID}"
    mkdir -p "$test_output_dir"
    
    echo -e "${BLUE}正在运行权限维持清理验证测试...${NC}"
    
    if python3 "$SCRIPT_DIR/persistence_cleanup_verifier.py" --output "$test_output_dir" 2>&1 | tee "$LOG_DIR/cleanup_test_${TEST_SESSION_ID}.log"; then
        log "INFO" "清理验证测试完成"
        return 0
    else
        log "ERROR" "清理验证测试失败"
        return 1
    fi
}

# 运行演示脚本
run_demo_script() {
    log "INFO" "开始运行演示脚本..."
    
    echo -e "${BLUE}正在运行权限维持演示脚本...${NC}"
    
    # 自动运行完整演示
    if echo "1" | bash "$SCRIPT_DIR/test_persistence_demo.sh" 2>&1 | tee "$LOG_DIR/demo_test_${TEST_SESSION_ID}.log"; then
        log "INFO" "演示脚本运行完成"
        
        # 等待一段时间让演示完成
        sleep 5
        
        # 自动清理演示环境
        echo -e "${YELLOW}正在清理演示环境...${NC}"
        echo "10" | bash "$SCRIPT_DIR/test_persistence_demo.sh" 2>&1 | tee -a "$LOG_DIR/demo_test_${TEST_SESSION_ID}.log"
        
        return 0
    else
        log "ERROR" "演示脚本运行失败"
        return 1
    fi
}

# 生成综合报告
generate_comprehensive_report() {
    log "INFO" "生成综合测试报告..."
    
    local report_file="$REPORT_DIR/comprehensive_test_report_${TEST_SESSION_ID}.md"
    
    cat > "$report_file" << EOF
# Linux权限维持一键化测试综合报告

## 测试概览

- **测试会话ID**: ${TEST_SESSION_ID}
- **测试时间**: $(date '+%Y-%m-%d %H:%M:%S')
- **测试环境**: $(uname -a)
- **Python版本**: $(python3 --version)

## 测试结果摘要

### 功能测试
EOF

    # 分析功能测试结果
    if [[ -f "$REPORT_DIR/functionality_${TEST_SESSION_ID}/test_report_${TEST_SESSION_ID}.json" ]]; then
        echo "- 状态: ✅ 完成" >> "$report_file"
        
        # 提取JSON中的成功率
        local success_rate=$(python3 -c "
import json
try:
    with open('$REPORT_DIR/functionality_${TEST_SESSION_ID}/test_report_${TEST_SESSION_ID}.json', 'r') as f:
        data = json.load(f)
    total = len(data.get('test_results', {}))
    success = sum(1 for result in data.get('test_results', {}).values() if result.get('status') == 'success')
    print(f'{success}/{total} ({success/total*100:.1f}%)' if total > 0 else '0/0 (0%)')
except:
    print('无法解析')
")
        echo "- 成功率: $success_rate" >> "$report_file"
    else
        echo "- 状态: ❌ 失败或未完成" >> "$report_file"
    fi

    cat >> "$report_file" << EOF

### 隐蔽性测试
EOF

    # 分析隐蔽性测试结果
    if [[ -f "$REPORT_DIR/stealth_${TEST_SESSION_ID}/stealth_check_${TEST_SESSION_ID}.json" ]]; then
        echo "- 状态: ✅ 完成" >> "$report_file"
        
        # 提取隐蔽性评分
        local stealth_score=$(python3 -c "
import json
try:
    with open('$REPORT_DIR/stealth_${TEST_SESSION_ID}/stealth_check_${TEST_SESSION_ID}.json', 'r') as f:
        data = json.load(f)
    print(data.get('stealth_score', 'N/A'))
except:
    print('无法解析')
")
        echo "- 隐蔽性评分: $stealth_score/100" >> "$report_file"
    else
        echo "- 状态: ❌ 失败或未完成" >> "$report_file"
    fi

    cat >> "$report_file" << EOF

### 清理验证测试
EOF

    # 分析清理验证结果
    if [[ -f "$REPORT_DIR/cleanup_${TEST_SESSION_ID}/cleanup_verification_${TEST_SESSION_ID}.json" ]]; then
        echo "- 状态: ✅ 完成" >> "$report_file"
        
        # 提取清理状态
        local cleanup_status=$(python3 -c "
import json
try:
    with open('$REPORT_DIR/cleanup_${TEST_SESSION_ID}/cleanup_verification_${TEST_SESSION_ID}.json', 'r') as f:
        data = json.load(f)
    print(data.get('overall_status', 'unknown'))
except:
    print('无法解析')
")
        echo "- 清理状态: $cleanup_status" >> "$report_file"
    else
        echo "- 状态: ❌ 失败或未完成" >> "$report_file"
    fi

    cat >> "$report_file" << EOF

## 详细结果

### 测试文件位置

- **功能测试报告**: \`$REPORT_DIR/functionality_${TEST_SESSION_ID}/\`
- **隐蔽性测试报告**: \`$REPORT_DIR/stealth_${TEST_SESSION_ID}/\`
- **清理验证报告**: \`$REPORT_DIR/cleanup_${TEST_SESSION_ID}/\`
- **演示脚本日志**: \`$LOG_DIR/demo_test_${TEST_SESSION_ID}.log\`

### 日志文件位置

- **主测试日志**: \`$LOG_DIR/run_all_tests_${TEST_SESSION_ID}.log\`
- **功能测试日志**: \`$LOG_DIR/functionality_test_${TEST_SESSION_ID}.log\`
- **隐蔽性测试日志**: \`$LOG_DIR/stealth_test_${TEST_SESSION_ID}.log\`
- **清理验证日志**: \`$LOG_DIR/cleanup_test_${TEST_SESSION_ID}.log\`

### 备份文件位置

- **系统状态备份**: \`$BACKUP_DIR/backup_${TEST_SESSION_ID}/\`

## 建议

1. 查看各个详细报告了解具体测试结果
2. 如有测试失败，检查对应的日志文件
3. 测试完成后，确认系统已恢复到原始状态
4. 定期运行测试以确保功能稳定性

---

*报告生成时间: $(date '+%Y-%m-%d %H:%M:%S')*
*测试工具版本: HackerPermKeeper T00ls v7.0*
EOF

    log "INFO" "综合报告已生成: $report_file"
}

# 清理测试环境
cleanup_test_environment() {
    log "INFO" "清理测试环境..."
    
    # 停止可能的测试服务
    systemctl stop test-* 2>/dev/null || true
    systemctl disable test-* 2>/dev/null || true
    
    # 删除测试文件
    rm -f /etc/systemd/system/test-* 2>/dev/null || true
    rm -f /usr/local/bin/test-* 2>/dev/null || true
    rm -f /etc/profile.d/.test-* 2>/dev/null || true
    
    # 重新加载systemd
    systemctl daemon-reload 2>/dev/null || true
    
    log "INFO" "测试环境清理完成"
}

# 显示测试结果摘要
show_test_summary() {
    echo -e "\n${GREEN}╔══════════════════════════════════════════════════════════════╗${NC}"
    echo -e "${GREEN}║                        测试完成摘要                          ║${NC}"
    echo -e "${GREEN}╚══════════════════════════════════════════════════════════════╝${NC}"
    
    echo -e "\n${CYAN}测试会话ID:${NC} $TEST_SESSION_ID"
    echo -e "${CYAN}测试时间:${NC} $(date '+%Y-%m-%d %H:%M:%S')"
    
    echo -e "\n${YELLOW}生成的文件:${NC}"
    echo -e "  📊 综合报告: ${REPORT_DIR}/comprehensive_test_report_${TEST_SESSION_ID}.md"
    echo -e "  📁 详细报告目录: ${REPORT_DIR}/"
    echo -e "  📋 日志目录: ${LOG_DIR}/"
    echo -e "  💾 备份目录: ${BACKUP_DIR}/backup_${TEST_SESSION_ID}/"
    
    echo -e "\n${YELLOW}查看报告命令:${NC}"
    echo -e "  cat ${REPORT_DIR}/comprehensive_test_report_${TEST_SESSION_ID}.md"
    
    echo -e "\n${GREEN}测试套件运行完成！${NC}"
}

# 主函数
main() {
    # 显示横幅
    show_banner
    
    # 检查参数
    local run_demo=true
    local run_cleanup=true
    
    while [[ $# -gt 0 ]]; do
        case $1 in
            --no-demo)
                run_demo=false
                shift
                ;;
            --no-cleanup)
                run_cleanup=false
                shift
                ;;
            --debug)
                export DEBUG=1
                shift
                ;;
            --help|-h)
                echo "用法: $0 [选项]"
                echo "选项:"
                echo "  --no-demo     跳过演示脚本"
                echo "  --no-cleanup  跳过清理步骤"
                echo "  --debug       启用调试模式"
                echo "  --help, -h    显示此帮助信息"
                exit 0
                ;;
            *)
                log "ERROR" "未知参数: $1"
                exit 1
                ;;
        esac
    done
    
    # 开始测试流程
    log "INFO" "开始Linux权限维持一键化测试套件 (会话ID: $TEST_SESSION_ID)"
    
    # 1. 检查系统要求
    check_requirements
    
    # 2. 备份系统状态
    backup_system_state
    
    local test_failed=false
    
    # 3. 运行功能测试
    if ! run_functionality_tests; then
        test_failed=true
    fi
    
    # 4. 运行隐蔽性测试
    if ! run_stealth_tests; then
        test_failed=true
    fi
    
    # 5. 运行清理验证测试
    if ! run_cleanup_tests; then
        test_failed=true
    fi
    
    # 6. 运行演示脚本 (可选)
    if [[ "$run_demo" == true ]]; then
        if ! run_demo_script; then
            test_failed=true
        fi
    fi
    
    # 7. 生成综合报告
    generate_comprehensive_report
    
    # 8. 清理测试环境 (可选)
    if [[ "$run_cleanup" == true ]]; then
        cleanup_test_environment
    fi
    
    # 9. 显示测试结果摘要
    show_test_summary
    
    # 检查是否有测试失败
    if [[ "$test_failed" == true ]]; then
        log "WARN" "部分测试失败，请检查日志文件"
        exit 1
    else
        log "INFO" "所有测试成功完成"
        exit 0
    fi
}

# 信号处理
trap 'log "ERROR" "测试被中断"; cleanup_test_environment; exit 1' INT TERM

# 运行主函数
main "$@"